package top.mask.mq.four;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import top.mask.mq.utils.RabbitMQUtil;

import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * 发布确认模式
 * 1.单个确认
 * 2.批量确认
 * 3.异步批量确认
 */
@Slf4j
public class ConfirmMessage {
    //批量发消息的个数
    public static final int MESSAGE_COUNT = 1000;

    @SneakyThrows
    public static void main(String[] args) {
        //1.单个确认
        //09:47:03.557 [main] INFO top.mask.mq.four.ConfirmMessage - 发布1000个单独消息,耗时181ms
        //publishMessageIndividually();
        //2.批量确认
        //09:58:44.557 [main] INFO top.mask.mq.four.ConfirmMessage - 发布1000个批量确认消息,耗时41ms
        //publishMessageBatch();

        //3.异步批量确认
        //10:23:50.115 [main] INFO top.mask.mq.four.ConfirmMessage - 发布1000个异步确认消息,耗时48ms
        publishMessageAsync();

    }


    /**
     * 单个确认模式
     * @throws Exception
     */
    public static void publishMessageIndividually() throws Exception {
        Channel channel = RabbitMQUtil.getChannel();
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);

        //开始时间
        //开启发布确认
        channel.confirmSelect();
        long begin = System.currentTimeMillis();

        //批量发消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("",queueName,null,message.getBytes());
            //单个消息就马上进行发布确认
            boolean flag = channel.waitForConfirms();
            if (flag){
                log.info("消息发送成功");
            }
        }

        //结束时间
        long end = System.currentTimeMillis();
        log.info("发布{}个单独消息,耗时{}ms",MESSAGE_COUNT,end-begin);


    }


    /**
     * 批量发布确认
     */
    @SneakyThrows
    public static void publishMessageBatch() {
        Channel channel = RabbitMQUtil.getChannel();
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);

        //开始时间
        //开启发布确认
        channel.confirmSelect();
        long begin = System.currentTimeMillis();

        //批量确认消息大小
        int batcSize = 100;

        //批量发消息,批量确认
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("",queueName,null,message.getBytes());
            //判断达到100条消息的时候,批量确认一次
            if (i % batcSize == 0){
                channel.waitForConfirms();
            }
        }

        //结束时间
        long end = System.currentTimeMillis();
        log.info("发布{}个批量确认消息,耗时{}ms",MESSAGE_COUNT,end-begin);

    }

    //异步发布确认
    @SneakyThrows
    public static void publishMessageAsync() {
        Channel channel = RabbitMQUtil.getChannel();
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);


        //开启发布确认
        channel.confirmSelect();

        /**
         * 线程安全有序的一个哈希表，适用于高并发的情况下
         * 1.轻松的将序号与消息进行关联
         * 2.轻松批量删除条目，只要给到序号
         * 3.支持高并发(多线程)
         */
        ConcurrentSkipListMap<Long,String> outStandingConfirms = new ConcurrentSkipListMap<>();



        //消息确认成功回调函数
        ConfirmCallback ackCallback = (deliveryTag,multiple) -> {
            if (multiple){
                //2.删除到已经确认的消息，剩下就是未确认的消息
                ConcurrentNavigableMap<Long, String> confirmed = outStandingConfirms.headMap(deliveryTag);
                confirmed.clear();
            }else {
                outStandingConfirms.remove(deliveryTag);
            }
            log.info("确认消息:[{}]",deliveryTag);
        };

        //消息确认失败回调函数
        ConfirmCallback nackCallback = (deliveryTag,multiple) -> {
            String message = outStandingConfirms.get(deliveryTag);

            //3.打印一下未确认的消息
            log.error("未确认消息:[{}],未确认的消息的标记tag[{}]",message,deliveryTag);
        };

        //准备消息的监听器
        channel.addConfirmListener(ackCallback,nackCallback);

        //开始时间
        long begin = System.currentTimeMillis();

        //批量发送消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = "消息" + i;
            channel.basicPublish("",queueName,null,message.getBytes());
            //1.此处记录下所有要发送的消息，消息的总和
            outStandingConfirms.put(channel.getNextPublishSeqNo(),message);
        }

        //结束时间
        long end = System.currentTimeMillis();
        log.info("发布{}个异步确认消息,耗时{}ms",MESSAGE_COUNT,end-begin);

    }


}
